package com.yuqiangz.springsecurity.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhaoyuqiang
 * @create 2024/5/17 7:27
 * @description  由于在认证过程中返回的是UserDetails接口类型，自己实现一个该类型
 */


@Data

@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    /**
     *
     permission
     同意 / 准许 / 正式批准文件 / 许可证
     */
    private List<String> permission;

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    public LoginUser(User user, List<String> permission) {
        this.user = user;
        this.permission = permission;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //优化效率不用每次都进行转换
        if(authorities != null){
            return authorities;
        }
        // //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities
        //中
        authorities = permission.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
